/*-
 * CSVWriter.java     v2.0  30-Jan-2005
 *
 * $LastChangedBy: stein $
 * $LastChangedRevision: 42 $
 * $LastChangedDate: 2006-12-02 03:13:47 +0000 (Sat, 02 Dec 2006) $
 * $HeadURL: svn://localhost/SMS/src/no/sgb/io/CSVWriter.java $
 *
 * Copyright (c) 2007, Stein Gunnar Bakkeby
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Stein Gunnar Bakkeby nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.googlecode.attention.io;

import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * CSV Writer, writes comma separated values to an output stream.
 *
 * @author Stein Gunnar Bakkeby
 */
public class CSVWriter {
  private String delim = ",";
  private boolean hasLabels = false;
  private String[] labels;
  private OutputStream stream;
  private boolean newStream = true;
  
  /**
   * Constructor, creates a default CSV Writer.
   * 
   * @see #setOutputStream(OutputStream)
   */
  public CSVWriter() {
    newStream = false;
  }
  
  /**
   * Constructor, creates the CSV Reader.
   * 
   * @param stream The input stream to read from
   * 
   */
  public CSVWriter(final OutputStream stream) {
    this.stream = stream;
  }

  /**
   * Sets the labels that describes the CSV data (optional).
   * 
   * @param labels The labels, must be the same amount as columns in CSV data
   */
  public void setLabels(final String[] labels) {
    this.labels = labels;
    this.hasLabels = true;
  }

  
  /**
   * This will write the CSV data to the output stream.
   * Note that this method only works once as the stream is closed
   * when writing has ended. If a new output stream is set then
   * this method will automatically work again.
   * 
   * @param values The CSV values (String[columns][rows])
   * @see #setOutputStream(OutputStream)
   */
  public void write(final String[][] values) {
    final int columns = values.length;
    final int rows = (columns != 0 ? values[0].length : 0);
    write(values, columns, rows);
  }
  
  /**
   * This will write the CSV data to the output stream.
   * Note that this method only works once as the stream is closed
   * when writing has ended. If a new output stream is set then
   * this method will automatically work again.
   * 
   * @param values The CSV values (String[columns][rows])
   * @param columns The number of columns in CSV data
   * @param rows The number of rows in CSV data
   * @see #setOutputStream(OutputStream)
   */
  public void write(final String[][] values,
                    final int columns,
                    final int rows) {
    if (!newStream) {
      return;
    }
    newStream = false;
    PrintWriter writer = new PrintWriter(stream);
    if (hasLabels) {
      for (int c = 0; c < columns; c++) {
        writer.print(labels[c] + (c + 1 == columns ? "\n" : delim));
      }
      hasLabels = false;
    }
    for (int r = 0; r < rows; r++) {
      for (int c = 0; c < columns; c++) {
        if (values[c][r].equals(delim)) {
          values[c][r] = "" + (char) 0;
        }
        writer.print(values[c][r] + (c + 1 == columns ? "\n" : delim));
      }
    }
    writer.close();
  }
  
  /**
   * This will write the CSV data to the output stream.
   * Note that this method only works once as the stream is closed
   * when writing has ended. If a new output stream is set then
   * this method will automatically work again.
   * 
   * @param values The CSV values (String[rows])
   * @see #setOutputStream(OutputStream)
   */
  public void write(final String[] values) {
    write(new String[][] {values}, 1, values.length);
  }
  
  /**
   * This will set the output stream, use this to reuse the 
   * CSVReader object.
   * 
   * @param stream The stream to write to
   */
  public void setOutputStream(final OutputStream stream) {
    this.stream = stream;
    this.newStream = true;
  }
  
  /**
   * Use this to close the input stream.
   * 
   * @throws IOException If any occurs
   */
  public void close() throws IOException {
    stream.close();
  }
  
  /**
   * This will set the delimiter (which separates the values),
   * the default value is comma &quot;,&quot;
   * 
   * @param delim The delimiter
   */
  public void setDelimiter(final String delim) {
    this.delim = delim;
  }
}